package com.ljl.question1;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

/**
 * 配置类
 *
 * @author ljl
 */
@Configuration
public class IntegrationConfiguration {
    private final Logger logger = LogManager.getLogger(IntegrationConfiguration.class);

    @Bean
    public MessageChannel inChannel1() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel outChannel1() {
        return new QueueChannel();
    }

    @Bean
    public IntegrationFlow p2p() {
        return IntegrationFlow.from(inChannel1())
                .transform(data -> data.toString().toUpperCase())
                .channel(outChannel1())
                .get();
    }

    @Bean
    public MessageChannel inChannel2() {
        return new PublishSubscribeChannel();
    }

    @Bean
    public IntegrationFlow ps1() {
        return IntegrationFlow.from(inChannel2())
                .handle(new MessageHandler() {
                    @Override
                    public void handleMessage(Message<?> message) throws MessagingException {
                        logger.info("ps1 receive msg:[{}]", message.getPayload());
                    }
                })
                .get();
    }

    @Bean
    public IntegrationFlow ps2() {
        return IntegrationFlow.from(inChannel2())
                .transform(data -> data.toString().toUpperCase())
                .handle(new MessageHandler() {
                    @Override
                    public void handleMessage(Message<?> message) throws MessagingException {
                        logger.info("ps2 receive msg:[{}]", message.getPayload());
                    }
                })
                .get();
    }
}
